const router = require('express').Router();
const AV = require('leanengine');
const Order = require('../order');
const wxpay = require('../wxpay');
const {validateSign} = require('../utils');
const requestjson = require('request-json');

const format = '___-_-_ _:_:__';
const formatTime = time =>
    new Date(
        time.split('')
            .map((value, index) => value + format[index])
            .join('').replace(/_/g, '')
    );

// 微信支付成功通知
router.post('/pay-callback', wxpay.useWXCallback((msg, req, res, next) => {
    // 处理商户业务逻辑
    validateSign(msg);
    const {
        result_code,
        err_code,
        err_code_des,
        out_trade_no,
        time_end,
        transaction_id,
        bank_type,
    } = msg;
    new AV.Query(Order).equalTo('number', out_trade_no).include('giver').first({
        useMasterKey: true,
    }).then(order => {
        var userName = order.toJSON().giver.nickName
        var orderId = order.toJSON().number
        var price = order.toJSON().itemPrice/100 +'元'
        var luckBug = '购买了一份'+order.toJSON().name+'福袋'
        if (!order) throw new Error(`找不到订单${out_trade_no}`);
        if (order.status === 'SUCCESS') return;
        sendTemplateMessage(userName,orderId,price,luckBug)
        return order.save({
            status: result_code,
            errorCode: err_code,
            errorCodeDes: err_code_des,
            paidAt: formatTime(time_end),
            transactionId: transaction_id,
            bankType: bank_type,
        }, {
            useMasterKey: true,
        });
    }).then(() => {
        res.success();
    }).catch(error => res.fail(error.message));
}));

function sendTemplateMessage(userName, orderId, price, luckBug) {
    let contents = {
        touser: "oyW8_0kn3GFkW3JWVQ1Q6GtRJbXw",
        template_id: "tE41V6SGQXDYsD0yuZawWADYyl6JTaNFW1Nif0SpKdY",
        data: {
            "first": {
                "value": "您的订单支付成功",
                "color": "#173177"
            },
            "keyword1": {
                "value": userName,
                "color": "#173177"
            },
            "keyword2": {
                "value": orderId,
                "color": "#173177"
            },
            "keyword3": {
                "value": price,
                "color": "#173177"
            },
            "keyword4": {
                "value": luckBug,
                "color": "#173177"
            },
            "remark": {
                "value": "欢迎再次购买！",
                "color": "#173177"
            }
        }
    }

    new AV.Query('Global')
        .get('5b4b08f8ee920a003c1026b4',{useMasterKey: true}).then(function (result) {
        var info = result.toJSON().value
        var access_token = JSON.parse(info).access_token
        try {
            var url = "/cgi-bin/message/template/send?access_token=";
            url += access_token;
            var client = requestjson.createClient('https://api.weixin.qq.com');
            client.post(url, contents, function (err, res, body) {
                console.log(res.statusCode, body);
            });
        } catch (e) {
            console.error(e.message);
            return e.message;
        }

    })
}

module.exports = router;
